<template>
  <div class="container">
    <h1>登录</h1>

    <p>用户名:demo 密码:demo</p>

    <div>
      <label for="email">
        <input id="email" type="email" v-model="username" />
      </label>
      <label for="password">
        <input id="password" type="password" v-model="password" />
      </label>

      <button @click="login">
        登录
      </button>
    </div>
  </div>
</template>

<script>
const Cookie = process.client ? require("js-cookie") : undefined;

export default {
  data: () => ({
    username: "demo",
    password: "demo"
  }),

  methods: {
    async login() {
      const { username, password } = this;

      const res = await this.$axios.$post("/api/login", { username, password });

      if (res.code !== 0) {
        this.$message.error("登录失败");
        return;
      }

      const token = { token: res.data.token };

      this.$store.commit("setToken", token);
      Cookie.set("token", token);
      this.$router.push("/");
    }
  }
};
</script>
